package com.qianfeng.user.controller;

import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.qianfeng.user.bean.Address;
import com.qianfeng.user.bean.User;
import com.qianfeng.user.service.AddressService;
import com.qianfeng.utils.Message;
import com.qianfeng.utils.Response;

@Controller
@RequestMapping("/address/")
public class AddressController {
	private AddressService addressService = new AddressService();

	@ResponseBody
	@RequestMapping("addAddress")
	public Response addAddress(HttpSession session, Address address) {
		// 这里只接收了一个id,但是传递给dao层的时候
		User user = (User) session.getAttribute("user");
		Response rs = new Response();
		if (user != null) {

			address.setUser_id(user.getId()); // 设置当前用户id

			boolean flg = addressService.saveAddress(address);// 保存信息
			if (flg) {
				rs.setCode(1);
			} else {
				rs.setCode(-1);
				rs.setMessage("对不起,添加失败");
			}
			return rs;
		} else {
			rs.setCode(Message.LOUT_CODE);
			return rs;
		}
	}

	@ResponseBody
	@RequestMapping("deleteById")
	public Response deleteById(HttpSession session, Address address) {
		// 这里只接收了一个id,但是传递给dao层的时候
		User user = (User) session.getAttribute("user");
		Response rs = new Response();
		if (user != null) {
			address.setUser_id(user.getId());
			boolean flg = addressService.deleteById(address);
			if (flg) {
				rs.setCode(1);
			} else {
				rs.setCode(-1);
				rs.setMessage("对不起,删除失败");
			}

			return rs;

		} else {
			rs.setCode(Message.LOUT_CODE);
			return rs;
		}
	}

	@ResponseBody
	@RequestMapping("updateAddressById")
	public Response updateAddressById(HttpSession session, Address address) {
		User user = (User) session.getAttribute("user");
		Response rs = new Response();
		if (user != null) {
			address.setUser_id(user.getId());
			boolean flg = addressService.updateAddress(address);
			if (flg) {
				rs.setCode(1);
			} else {
				rs.setCode(-1);
				rs.setMessage("对不起,添加失败");
			}
			return rs;

		} else {
			rs.setCode(Message.LOUT_CODE);
			return rs;
		}
	}

	@ResponseBody
	@RequestMapping("addressChangeDefault")
	public String addressChangeDefault(HttpSession session, Address address) {
		User user = (User) session.getAttribute("user");
		if (user != null) {

			address.setUser_id(user.getId()); // 设置当前用户id

			addressService.addressChangeDefault(address);

			return "redirect:/user/toUserInfoPage";

		} else {
			return "login";
		}
	}
}
